package iterator;

import factory.A;

/**
 * 数据存储在物理的层面上只有两种 Array 链表 这俩是物理结构。
 * 其它所有的容器底层都是这两种实现的 他们是逻辑结构
 *
 * 这里写的有瑕疵 其实应该是迭代器有个iterator的方法 然后返回一个实现了 Iterator_接口的类 然后用迭代器去遍历。
 * 跟遍历有关的内容都应该放到返回的内部类里面。
 *
 * 范型字母意义
 * E Element
 * T Type
 * V Value
 */
public class Iterator {
    public static void main(String[] args){
        System.out.println("Sys");

        ArrayList_ a = new ArrayList_();

        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());
        a.add(new Object());

        System.out.println(a.getNum());
        int i = 0;
        while (a.hasNext()){
            System.out.println(a.next()+"i="+(i++));
        }

        LinkList_ listx = new LinkList_();
        listx.add(new Object());
        listx.add(new Object());
        listx.add(new Object());
        listx.add(new Object());
        System.out.println(listx.getSize());

        while (listx.hasNext()){
            System.out.println(listx.next());
        }

    }
}

interface Iterator_{
    boolean hasNext();
    Object next();
}


class ArrayList_ implements Iterator_{
    private Object[] list = new Object[2];
    private int num = 0;
    private int readFlg = 0;

    public int add(Object item){
        // System.out.println(list.length+"-------@@");
        if(num >= list.length){
            System.out.println("扩容");
            Object[] k = new Object[list.length*5];
            System.arraycopy(list,0,k,0,list.length);
            list = k;
        }

        list[num] = item;
        num++;

        return num;
    }

    public int getNum(){
        return num;
    }

    @Override
    public boolean hasNext() {
        return readFlg < list.length;
    }

    @Override
    public Object next() {
        return list[readFlg++];
    }
}

class Node{
    private Object o;
    public Node(Object o){
        this.o = o;
    }
    Node next;
}

class LinkList_ implements Iterator_{
    private Node head = null;
    private Node tail = null;
    private Node read = null;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public int add(Object o){

        // 创建节点
        Node node = new Node(o);
        node.next = null;

        if(null == head){
            head = node;
            tail = node;
            read = node;
        }else{
            tail.next = node;
            tail = node;
        }

        size++;
        return size;
    }

    @Override
    public boolean hasNext() {
        return null != read;
    }

    @Override
    public Object next() {
        Object o = read;
        read = read.next;
        return o;
    }
}